package cn.classTest.mall.shiro;

import cn.classTest.mall.domain.Employee;
import cn.classTest.mall.domain.Role;
import cn.classTest.mall.service.EmployeeService;
import cn.classTest.mall.service.RoleService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component("authorizer") //将RbacRealm加别名，添加给容器中
public class RbacRealm extends AuthorizingRealm {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;

    //提供授权信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取subject对象
        Subject subject = SecurityUtils.getSubject();
        //判断当前登录的用户是否拥有超级管理员的权限
        Employee employee = (Employee) subject.getPrincipal();

        if (employee.isAdmin()) {
            info.addStringPermission("*:*");
            List<Role> roles = roleService.selectAll();
            roles.forEach(role -> info.addRole(role.getSn()));
            return info;
        }
        //根据员工id查询员工所拥有的权限和角色
        List<Role> roles = roleService.selectRoleByEmployeeId(employee.getId());
        roles.forEach(role -> info.addRole(role.getSn()));

        //根据角色id 获取员工对应的角色的权限，并添加到set集合中
        List<String> expressions = employeeService.selectExpressionsById(employee.getId());
        info.addStringPermissions(expressions);
        return info;
    }

    //提供认证信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //通过username在数据库中查询真实数据，
        Object username = authenticationToken.getPrincipal();
        Employee employee = employeeService.selectByUsername((String) username);
        if (employee != null) {
            return new SimpleAuthenticationInfo(employee, employee.getPassword(), employee.getName());
        }
        return null;
    }
}
